package cre.tomcat7.ch09.core;

import org.apache.catalina.*;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author penglai
 * @Date 2017/1/27.
 */
public class SimpleWrapperValve implements Valve, Contained {

    private Container container;

    public String getInfo() {
        return "Simple WrapperValve";
    }

    public void invoke(Request request, Response response, ValveContext valveContext) throws IOException, ServletException {
        ServletRequest servletRequest = request.getRequest();
        ServletResponse servletResponse = response.getResponse();

        HttpServletRequest httpServletRequest = null;
        HttpServletResponse httpServletResponse = null;

        if (servletRequest instanceof HttpServletRequest) {
            httpServletRequest = (HttpServletRequest) servletRequest;
        }
        if (servletResponse instanceof HttpServletResponse) {
            httpServletResponse = (HttpServletResponse) servletResponse;
        }

        Wrapper wrapper = (Wrapper) getContainer();
        Servlet servlet = null;

        Context context = (Context) wrapper.getParent();
        request.setContext(context);
        try {
            servlet = wrapper.allocate();
            if (httpServletRequest != null && httpServletResponse != null) {
                servlet.service(httpServletRequest, httpServletResponse);
            } else {
                servlet.service(servletRequest, servletResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Container getContainer() {
        return container;
    }

    public void setContainer(Container container) {
        this.container = container;
    }
}
